// pages/wardrobe/wardrobe.js - 真实衣柜样式
Page({
  data: {
    loading: true,
    categories: [],
    totalItems: 0,

    // 衣柜区域开关状态
    openSections: {
      tops: false,        // 上衣
      bottoms: false,     // 裤子裙子
      outerwear: false,   // 外套
      accessories: false, // 配饰
      shoes: false,       // 鞋子
      custom: false       // 自定义
    },

    // 各区域的商品
    sectionProducts: {
      tops: [],
      bottoms: [],
      outerwear: [],
      accessories: [],
      shoes: [],
      custom: []
    },

    // 弹窗状态
    showCategoryModal: false,
    showMoveModal: false,
    newCategoryName: '',
    selectedProduct: null,
    targetSection: null
  },

  onLoad(options) {
    this.loadWardrobeData();
  },

  onShow() {
    this.loadWardrobeData();
  },

  // 加载衣橱数据
  loadWardrobeData() {
    this.setData({ loading: true });

    Promise.all([
      this.loadCategories(),
      this.loadFavoriteProducts()
    ]).then(() => {
      this.organizeSectionProducts();
      this.setData({ loading: false });
    }).catch(err => {
      console.error('加载衣橱数据失败:', err);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({ loading: false });
    });
  },

  // 加载分类列表
  loadCategories() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.example.com/categories',
        method: 'GET',
        header: {
          'Authorization': wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.setData({
              categories: res.data.data || []
            });
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '获取分类失败'));
          }
        },
        fail: reject
      });
    });
  },

  // 加载收藏商品
  loadFavoriteProducts() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.example.com/favorites',
        method: 'GET',
        header: {
          'Authorization': wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            const products = res.data.data || [];
            this.setData({
              totalItems: products.length
            });
            resolve(products);
          } else {
            reject(new Error(res.data.message || '获取收藏商品失败'));
          }
        },
        fail: reject
      });
    });
  },

  // 切换衣柜区域开关
  toggleSection(e) {
    const section = e.currentTarget.dataset.section;
    const openSections = { ...this.data.openSections };

    // 切换当前区域状态
    openSections[section] = !openSections[section];

    this.setData({ openSections });
  },

  // 整理分区商品
  organizeSectionProducts() {
    const { categories } = this.data;
    const sectionProducts = {
      tops: [],
      bottoms: [],
      outerwear: [],
      accessories: [],
      shoes: [],
      custom: []
    };

    // 遍历所有分类和商品，按服装类型分配到不同区域
    categories.forEach(category => {
      if (category.products && category.products.length > 0) {
        category.products.forEach(product => {
          const clothesType = product.clothesType || '';

          // 根据服装类型分配到对应区域
          if (clothesType.includes('Upper-body') || clothesType.includes('上衣') || clothesType.includes('T恤') || clothesType.includes('衬衫')) {
            sectionProducts.tops.push(product);
          } else if (clothesType.includes('Lower-body') || clothesType.includes('裤子') || clothesType.includes('裙子') || clothesType.includes('短裤')) {
            sectionProducts.bottoms.push(product);
          } else if (clothesType.includes('外套') || clothesType.includes('夹克') || clothesType.includes('大衣') || clothesType.includes('风衣')) {
            sectionProducts.outerwear.push(product);
          } else if (clothesType.includes('配饰') || clothesType.includes('帽子') || clothesType.includes('包') || clothesType.includes('首饰')) {
            sectionProducts.accessories.push(product);
          } else if (clothesType.includes('鞋') || clothesType.includes('靴') || clothesType.includes('凉鞋') || clothesType.includes('运动鞋')) {
            sectionProducts.shoes.push(product);
          } else {
            // 未分类的商品放入自定义区域
            sectionProducts.custom.push(product);
          }
        });
      }
    });

    this.setData({ sectionProducts });
  },

  // 显示分类管理弹窗
  showCategoryModal() {
    this.setData({
      showCategoryModal: true,
      newCategoryName: ''
    });
  },

  // 隐藏分类管理弹窗
  hideCategoryModal() {
    this.setData({
      showCategoryModal: false,
      newCategoryName: ''
    });
  },

  // 输入分类名称
  onCategoryNameInput(e) {
    this.setData({
      newCategoryName: e.detail.value
    });
  },

  // 添加分类
  addCategory() {
    const { newCategoryName } = this.data;
    
    if (!newCategoryName.trim()) {
      wx.showToast({
        title: '请输入分类名称',
        icon: 'error'
      });
      return;
    }

    wx.request({
      url: 'https://api.example.com/categories',
      method: 'POST',
      header: {
        'Authorization': wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: {
        categoryName: newCategoryName.trim()
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          this.hideCategoryModal();
          this.loadWardrobeData();
        } else {
          wx.showToast({
            title: res.data.message || '添加失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        });
      }
    });
  },

  // 编辑分类
  editCategory(e) {
    const category = e.currentTarget.dataset.category;
    // 这里可以实现编辑功能
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },

  // 删除分类
  deleteCategory(e) {
    const category = e.currentTarget.dataset.category;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除分类"${category.categoryName}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performDeleteCategory(category.categoryId);
        }
      }
    });
  },

  // 执行删除分类
  performDeleteCategory(categoryId) {
    wx.request({
      url: `https://api.example.com/categories/${categoryId}`,
      method: 'DELETE',
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          this.loadWardrobeData();
        } else {
          wx.showToast({
            title: res.data.message || '删除失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        });
      }
    });
  },

  // 查看商品详情
  viewProduct(e) {
    const product = e.currentTarget.dataset.product;
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?productId=${product.productId}`
    });
  },

  // 切换收藏状态
  toggleProductFavorite(e) {
    const item = e.currentTarget.dataset.item;
    
    wx.request({
      url: 'https://api.example.com/favorites/toggle',
      method: 'POST',
      header: {
        'Authorization': wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: {
        productId: item.productId
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({
            title: item.favorited ? '已取消收藏' : '已收藏',
            icon: 'success'
          });
          this.loadWardrobeData();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        });
      }
    });
  },

  // 试穿功能
  tryOnClothing(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/try-on/try-on?productId=${item.productId}`
    });
  },

  // 移动商品
  moveProduct(e) {
    const product = e.currentTarget.dataset.product;
    this.setData({
      selectedProduct: product,
      showMoveModal: true,
      targetSection: null
    });
  },

  // 隐藏移动弹窗
  hideMoveModal() {
    this.setData({
      showMoveModal: false,
      selectedProduct: null,
      targetSection: null
    });
  },

  // 选择移动目标区域
  selectMoveSection(e) {
    const section = e.currentTarget.dataset.section;
    this.setData({
      targetSection: section
    });
  },

  // 确认移动商品
  confirmMoveProduct() {
    const { selectedProduct, targetSection } = this.data;

    if (!targetSection) {
      wx.showToast({
        title: '请选择目标区域',
        icon: 'error'
      });
      return;
    }

    // 这里可以调用API更新商品的clothesType
    // 暂时模拟移动成功
    wx.showToast({
      title: '移动成功',
      icon: 'success'
    });

    this.hideMoveModal();

    // 重新整理分区商品
    setTimeout(() => {
      this.organizeSectionProducts();
    }, 500);
  }
});
